/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.aaron.platform.service;

import com.aaron.platform.common.ItscCheckedException;
import javax.mail.Message;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import org.apache.log4j.Logger;
import org.springframework.core.task.TaskExecutor;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import com.aaron.platform.exceptions.MailReceiversNotExistException;
import com.aaron.platform.exceptions.MailSendFailException;
import java.util.logging.Level;
import javax.mail.MessagingException;
import org.apache.commons.lang.StringUtils;


/**
 *
 * @author aaronbamboo
 */
public class MailServiceImp implements MailService {
    
    private static Logger logger = Logger.getLogger(MailServiceImp.class);
    
    private JavaMailSender mailSender;
    
    private TaskExecutor taskExecutor;

    public void sendHtmlEmailsByAsyn(ItscMailMessage mailMessage) {
        this.sendMailByAsynchronizationMode(mailMessage);
    }

    public void sendHtmlEmailsBySyn(ItscMailMessage mailMessage) {
        try {
            this.sendMailBySynchronizationMode(mailMessage);
        } catch (ItscCheckedException ex) {
            java.util.logging.Logger.getLogger(MailServiceImp.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    
    private void sendMailBySynchronizationMode(ItscMailMessage mailMessage) throws ItscCheckedException {
        
        // 邮件接收人不能为空
        if (mailMessage.getMailReceivers() == null || mailMessage.getMailReceivers().isEmpty()) {
            throw new MailReceiversNotExistException(mailMessage.getMailFrom());
        } 
        
        // 设置内容
        try {
        InternetAddress[] toAddress = new InternetAddress[mailMessage.getMailReceivers().size()];
        for (int i = 0; i < mailMessage.getMailReceivers().size(); i++) {
            toAddress[i] = new InternetAddress(mailMessage.getMailReceivers().get(i));
        }
        
        MimeMessage mimeMessage = mailSender.createMimeMessage();
        MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMessage, "utf-8");
        
            mimeMessage.setRecipients(Message.RecipientType.TO, toAddress);
        
        messageHelper.setFrom(mailMessage.getMailFrom());
        if (StringUtils.isNotEmpty(mailMessage.getSubject())) {
            messageHelper.setSubject(mailMessage.getSubject());
        } else {
             messageHelper.setSubject("");
        }
        
        if (StringUtils.isNotEmpty(mailMessage.getContent())) {
            messageHelper.setText(mailMessage.getContent());
        } else {
             messageHelper.setText("");
        }
        
        // 发送邮件
        mailSender.send(mimeMessage);
         } catch (MessagingException ex) {
            throw new MailSendFailException(mailMessage.getMailFrom());
        }
    }
    
    private void sendMailByAsynchronizationMode(final ItscMailMessage mailMessage) {
        
        if (logger.isDebugEnabled()) {
            logger.debug("send by asynchronization mode");
	}
        
        // 异步调用
        taskExecutor.execute(new Runnable() {
            public void run() {
                try {
                    sendMailBySynchronizationMode(mailMessage);
                } catch (ItscCheckedException ex) {
                    java.util.logging.Logger.getLogger(MailServiceImp.class.getName()).log(Level.SEVERE, null, ex);
                }
              
            }
        });
    }

    public void setMailSender(JavaMailSender mailSender) {
        this.mailSender = mailSender;
    }

    public void setTaskExecutor(TaskExecutor taskExecutor) {
        this.taskExecutor = taskExecutor;
    }
}
